package com.leenmvc.core.dao.iotdb.connect;

import com.leenmvc.core.utils.spring.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库连接池管理
 */
public class IOTdbConnectionFactory {

    private final static Logger logger = LoggerFactory.getLogger(IOTdbConnectionFactory.class);

    /**
     * 根据sql
     * <p>
     * 动态获取数据库连接和mybatis的SqlSessionFactory
     *
     * @return
     */
    public static Connection getConnection() {
        try {
            DataSource dataSource = null;
            dataSource = SpringContextUtils.getBean("dataSource_iotdb", DataSource.class);
            return dataSource.getConnection();
        } catch (SQLException e) {
            logger.info(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 关闭操作
     *
     * @param result
     * @param preparedStatement
     * @param conn
     */
    public static void close(ResultSet result, PreparedStatement preparedStatement, Connection conn) {
        try {
            if (result != null) result.close();
            if (preparedStatement != null) preparedStatement.close();
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            logger.info(e.getMessage(), e);
        }
    }



    public static void closeConnection(Connection connection){
        try {
            if(null != connection){
                connection.close();
            }
        } catch (SQLException e) {
            logger.info(e.getMessage(), e);
        }
    }

}
